<template>

	<view class="myindex">
		<view class="myindex-k">
			<view class="myindex-tx">
				<u-upload :action="action" :file-list="fileList" width="150" height="150" upload-text='请上传'
					:max-count="1" :form-data="udformdata" :before-upload="beforeUpload" @on-success="onsuccessback"
					@on-remove="onremoveback" :show-progress="false"></u-upload>

			</view>
			<u-form :model="form" ref="uForm" label-width="140">
				<!-- <u-form-item label="头像" prop="userHead">
				<u-upload :action="action" :file-list="fileList" width="150" height ="150" upload-text='请上传'
				 :max-count="1"  
				 :form-data="udformdata" 
				 :before-upload="beforeUpload"
				 @on-success="onsuccessback"
				 @on-remove="onremoveback"
				  :show-progress="false"
				></u-upload>
				</u-form-item> -->
				<u-form-item label="昵称" prop="userName"><u-input v-model="form.userName" /></u-form-item>

				<u-form-item label="工号" prop="userCode"><u-input v-model="form.userCode" :disabled="true"
						placeholder=" " /></u-form-item>
				<u-form-item label="手机号" prop="userMobile"><u-input v-model="form.userMobile"
						:disabled="true" /></u-form-item>

				<u-form-item label="企业归属" prop="userOffice"><u-input v-model="form.userOffice" /></u-form-item>

			</u-form>
			<view style="height: 120rpx;">

			</view>
			<u-button @click="submit">提交</u-button>
		</view>


	</view>
</template>

<script>
	import {
		BASE_URL_IMAHE,
		BASE_URL
	} from "../../../utils/https";
	import {
		getUserInfo,
		updateUserInfo
	} from "@/api/index/index";

	export default {
		data() {
			return {
				fileList: [],
				form: {
					userId: "",
					userHead: "",
					userName: "",
					userOffice: "",
				},
				action: BASE_URL + '/saveFileUploads',
				udformdata: {
					userId: ''
				},
				rules: {
					userHead: [{
						required: true,
						message: '请上传头像',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					userName: [{
						required: true,
						message: '请输入昵称,',
						trigger: 'change'
					}],
					userOffice: [{
						required: true,
						message: '请输入企业归属,',
						trigger: 'change'
					}],

				},
			};
		},
		onLoad() {
			this.getUserInfofun()
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},

		methods: {
			async getUserInfofun() {
				const res = await getUserInfo(JSON.stringify({
					userId: uni.getStorageSync("userId")
				}))
				console.log(res)
				var tel = res.user.userMobile;
				tel = "" + tel;
				var tel1 = tel.substr(0, 3) + "****" + tel.substr(7)
				this.form = {
					userName: res.user.userName,
					userOffice: res.user.userOffice,
					userHead: res.user.userHead,
					userId: res.user.id,
					userCode: res.user.userCode ? res.user.userCode : "",
					userMobile: tel1

				}
				this.fileList.push({
					url: BASE_URL_IMAHE + res.user.userHead
				})

			},

			submit() {
				var that = this
				this.$refs.uForm.validate(async valid => {
					if (valid) {
						console.log('验证通过');
						var res = await updateUserInfo(JSON.stringify(that.form))
						console.log(res)
						if (res.result == 0) {
							uni.showToast({
								title: "修改成功",
								icon: "none"
							})
							// uni.setStorageSync("userMobile",Registe.user.userCode)
							// uni.setStorageSync("userRef",Registe.user.userRef)

							uni.setStorageSync("userName", that.form.userName)
							uni.setStorageSync("userOffice", that.form.userOffice)
							uni.setStorageSync("userHead", that.form.userHead)
							uni.setStorageSync("userCode", that.form.userCode ? that.form.userCode : "")
							console.log("that.form", that.form)

						}
						setTimeout(() => {
							uni.redirectTo({
								url: "/pages/home/index"
							})
						}, 1500)
					} else {
						console.log('验证失败');
					}
				});
			},
			beforeUpload(file, list) {
				console.log("e")
				uni.showLoading({
					title: "上传中",
					mask: true,

				})
				this.compressImage(file)

			},
			compressImage(file) {
				// 创建一个新的Promise，在压缩图片后解决
				return new Promise((resolve, reject) => {
					const reader = new FileReader()
					reader.onload = (e) => {
						const img = new Image()
						img.onload = () => {
							// 假设我们要将图片压缩到原始尺寸的一半
							const canvas = document.createElement('canvas')
							canvas.width = img.width / 2
							canvas.height = img.height / 2
							const ctx = canvas.getContext('2d')
							ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
							canvas.toBlob(
								(blob) => {
									if (blob) {
										// 将压缩后的图片转换为新的File对象
										resolve(new File([blob], file.name, {
											type: file.type
										}))
									} else {
										reject(new Error('Compress failed'))
									}
								},
								file.type,
								0.5
							) // 0.5为图片质量
						}
						img.src = e.target.result
					}
					reader.onerror = reject
					reader.readAsDataURL(file)
				})
			},

			onsuccessback(data, index, lists, name) {
				console.log(data, index, lists, name)
				this.form.userHead = data.fileUrls[0]

			},

			onremoveback(index, lists, name) {
				console.log(index, lists, name)
				this.form.userHead = ""
			},
		}
	};
</script>

<style>
	.myindex {
		padding-top: 50rpx;
	}

	.myindex-k {
		width: 710rpx;
		margin: 0 auto;
		background-color: white;
		box-sizing: border-box;
		padding: 30rpx 30rpx;
		border-radius: 40rpx;
	}

	.myindex-tx {
		display: flex;
		justify-content: center;

	}

	.myindex-gh {}
</style>